package com.alstudio.ui.module.user;

import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALPhoto;
import com.alstudio.module.xmpp.protocol.xmpp.data.VauthData;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.ui.base.BaseActivity.TimeOutListener;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.utils.android.ALFileManager;
import com.alstudio.utils.android.ALSdcardManager;
import com.alstudio.utils.android.imageProcess.ALImageProcessParams;
import com.alstudio.utils.android.net.http.UploadPhotoRequest;
import com.alstudio.utils.formater.numeric.ALNumericUtils;
import com.alstudio.utils.umeng.UmengUtils;
import com.alstudio.view.dialog.AlertDialogCreator;
import com.loovee.imaohu.R;
import com.umeng.analytics.MobclickAgent;

public class NewVauthActivity extends TitleBarActivity implements
		TimeOutListener {

	private Button submit;
	private ImageView takePhoto, selectPhoto;
	private Bitmap takeImage, selectImage;

	private SubmitVAuthStep submitStep = SubmitVAuthStep.AL_SUBMIT_VAUTH_NONE;
	private String takePhotoPath;
	private String selectPhotoFileid;
	private String largeUrl;
	private String smallurl;
	private String pos;
	public static final int SELECT_MY_PHOTO = 10011;
	// private ImageWorkerManager mImageWorker;
	// private ImageParam gridIparam;
	private boolean isTakePhoto = false;
	private boolean isSelectPhoto = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setupView(this, getClass().getSimpleName());
		requeqtData();
	}

	@Override
	protected void setupView(Context v, String tag) {
		// TODO Auto-generated method stub
		super.setupView(v, tag);
		setTitleBarActivityContentView(R.layout.new_vauth_layout);
		setCenterTextViewMessage(R.string.TxtVauthTitle);

		submit = (Button) findViewById(R.id.submit);
		takePhoto = (ImageView) findViewById(R.id.take_photo);
		selectPhoto = (ImageView) findViewById(R.id.select_photo);

		takePhoto.setOnClickListener(this);
		selectPhoto.setOnClickListener(this);
		submit.setOnClickListener(this);
		findViewById(R.id.info).setOnClickListener(this);
//		setTextInfo();
	}

	@Override
	public void requeqtData() {
		// TODO Auto-generated method stub
		super.requeqtData();
		if (ALLocalEnv.isSendXmppDataEnable()) {
			showLoadingProgress();
			// 获取V认证状态
			ALUiXmppRequestCreator.postALUiXmppCheckVauthState();
		}
		// ---------------------tody.yang---2013.08.27结束-------------------------
	}

	@Override
	protected void showProgressBar(ProgressBar bar) {
		// TODO Auto-generated method stub
		super.showProgressBar(bar);
		sendTimeoutEvent(this);
	}

	@Override
	protected void dismissProgressBar(ProgressBar bar) {
		// TODO Auto-generated method stub
		super.dismissProgressBar(bar);
	}

	@Override
	protected void onGetProcessPhotosResult(String path, String name) {
		// TODO Auto-generated method stub
		super.onGetProcessPhotosResult(path, name);
		switch (submitStep) {
		case AL_SUBMIT_VAUTH_SELECT_PHOTO:
			break;
		case AL_SUBMIT_VAUTH_TAKE_PHOTO:
			doUpload(path, name);
			break;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.take_photo:
			submitStep = SubmitVAuthStep.AL_SUBMIT_VAUTH_TAKE_PHOTO;
			doTakePhoto();
			break;
		case R.id.select_photo:
			submitStep = SubmitVAuthStep.AL_SUBMIT_VAUTH_SELECT_PHOTO;
			doSelectPhoto();
			break;
		case R.id.submit:
			submitStep = SubmitVAuthStep.AL_SUBMIT_VAUTH_SUBMIT;
			doSubmit();
			break;
		case R.id.info:
			// 跳到玩转对面
			// WebViewManager.getInstance().gotoPlayMeachActivity(
			// NewVauthActivity.this, WebViewManager.V_AUTH);
			break;
		}
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (selectImage != null) {
			if (!selectImage.isRecycled()) {
				selectImage.recycle();
				selectImage = null;
			}
		}

		if (takeImage != null) {
			if (!takeImage.isRecycled()) {
				takeImage.recycle();
				takeImage = null;
			}
		}
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		mhandler.removeCallbacks(uploadPicSuccessHandler);
		cancelTimeoutEvent();
		try {
			UmengUtils.markEvent(this,
					UmengUtils.Event.CLICK_AUTH_VIEW_OPEN_COUNT, null, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public void onTimeout() {
		// TODO Auto-generated method stub
		// dismissProgressBar(mProgressBar);
		dismissLoadingProgress();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
		case SELECT_MY_PHOTO:
			// 拍照返回
			String pos = intent.getStringExtra("postion");
			String fileid = intent.getStringExtra("fileid");
			doSelectedPhotoResult(pos, fileid);
			break;
		}
	}

	private void doTakePhoto() {

		UmengUtils.markEvent(this,
				UmengUtils.Event.CLICK_AUTH_VIEW_CAMERA_COUNT, null, null);

		ALImageProcessParams param = new ALImageProcessParams();
		param.setRequestHeight(640);
		param.setRequestWidth(640);
		param.setExplicitCrop(false);
		// 文件保存位置
		param.setSavePath(ALSdcardManager.getExtStoragePath());
		takePhotos(param);
	}

	private void doSelectPhoto() {
		UmengUtils.markEvent(this,
				UmengUtils.Event.CLICK_AUTH_VIEW_COMPARISON_COUNT, null, null);
		Intent i = new Intent(this, PhotoActivity.class);
		i.putExtra("selectMyPhoto", true);
		startActivityForResult(i, SELECT_MY_PHOTO);
	}

	private void doUpload(String path, String name) {

		if (!ALFileManager.isFileExsit(path))
			return;

		showLoadingProgress();
		// 上传头像
		uploadPic(path);
		takePhotoPath = path;
		Uri s = Uri.fromFile(new File(takePhotoPath));
		ALLocalEnv.getLocalEnv().getImageLoader()
				.displayImage(s.toString(), takePhoto);
	}

	private void doSubmit() {
		UmengUtils.markEvent(this,
				UmengUtils.Event.CLICK_AUTH_VIEW_SUBMIT_COUNT, null, null);
		if (!isSubmitReady()) {
			showDialog(getString(R.string.Txteminder),
					getString(R.string.TxtVauthReauthAlert));
			return;
		}

		if (ALLocalEnv.isSendXmppDataEnable()) {
			resetVauthPos();
			// 成功，请求认证
			showLoadingProgress();
			VauthData data = new VauthData();
			data.setUrl(largeUrl);
			data.setSmallUrl(smallurl);
			data.setIndex(pos);
			data.setSelectPhotoFileid(selectPhotoFileid);
			ALUiXmppRequestCreator.postALUiXmppStartVauth(data);
		}

	}

	private void resetVauthPos() {
		int vPos = ALLocalEnv.getLocalEnv().getMyProfile().getvAuthPos();

		if (vPos != -1
				&& vPos < ALLocalEnv.getLocalEnv().getMyProfile().getPhotos()
						.size()) {
			ALPhoto p = ALLocalEnv.getLocalEnv().getMyProfile().getPhotos()
					.get(vPos);
			p.setVauth(false);
			ALLocalEnv.getLocalEnv().getMyProfile().setvAuthPos(-1);
		}

		vPos = ALNumericUtils.parseInt(pos, -1);

		if (vPos != -1) {
			ALPhoto p = ALLocalEnv.getLocalEnv().getMyProfile().getPhotos()
					.get(vPos);
			p.setVauth(true);
			ALLocalEnv.getLocalEnv().getMyProfile().setvAuthPos(vPos);
		}
	}

	private void doSelectedPhotoResult(String pos, String fileid) {
		isSelectPhoto = true;
		this.pos = pos;
		selectPhotoFileid = ALLocalEnv.getBareFileId(fileid);
		setImage(selectPhotoFileid, selectPhoto);
		if (v_state != AUTHETICATIONING)
			checkSubmitReady();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.TitleBarActivity#handleUploadPicSuccess(com.alstudio
	 * .utils.android.net.http.UploadPhotoRequest, java.lang.String,
	 * java.lang.String)
	 */
	@Override
	protected void handleUploadPicSuccess(UploadPhotoRequest sender,
			String pictureFileId, String thumbFileId) {
		// TODO Auto-generated method stub
		super.handleUploadPicSuccess(sender, pictureFileId, thumbFileId);
		dismissLoadingProgress();
		if (!TextUtils.isEmpty(sender.getFilepath())) {
			if (takePhotoPath != null) {
				if (takePhotoPath.equals(sender.getFilepath())) {
					largeUrl = pictureFileId;
					smallurl = thumbFileId;
					isTakePhoto = true;
					mhandler.post(uploadPicSuccessHandler);
				}
			}
		}
	}

	private Runnable uploadPicSuccessHandler = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			checkSubmitReady();
		}
	};

	private boolean checkSubmitReady() {
		if (isSubmitReady()) {
			submit.setEnabled(true);
			return true;
		} else {
			submit.setEnabled(false);
			return false;
		}
	}

	private boolean isSubmitReady() {

		if (v_state == AUTHETICATIONING && isTakePhoto && isPhotoToken()) {
			return true;
		}

		if (isTakePhoto && isSelectPhoto && isPhotoToken() && isPhotoSelected()) {
			return true;
		}

		return false;

	}

	private boolean isPhotoToken() {
		if ((!TextUtils.isEmpty(largeUrl) && !TextUtils.isEmpty(smallurl))) {
			return true;
		}
		return false;
	}

	private boolean isPhotoSelected() {
		if (!TextUtils.isEmpty(selectPhotoFileid) && !TextUtils.isEmpty(pos)) {
			return true;
		}
		return false;
	}

	private int v_state = -1;
	private final int NO_AUTHETICATION = 0;
	private final int ALREADY_AUTHETICATION = 1;
	private final int AUTHETICATIONING = 2;

	// 设置按钮状态
	private void setAutheticationState(VauthData intent) {

//		v_state = ALLocalEnv.getLocalEnv().getMyProfile().getVauthed();
		v_state = intent.getStatus();
		switch (v_state) {
		case NO_AUTHETICATION:
			submit.setText(R.string.BtnSubmitVauth);
			takePhoto.setClickable(true);
			selectPhoto.setClickable(true);
			break;
		case ALREADY_AUTHETICATION:
			submit.setText(R.string.TxtAlreadyAuthed);
			takePhoto.setClickable(false);
			selectPhoto.setClickable(false);
			;
			break;
		case AUTHETICATIONING:
			submit.setText(R.string.TxtAutheticationVerify);
			isSelectPhoto = true;
			submit.setEnabled(true);
			takePhoto.setClickable(true);
			selectPhoto.setClickable(true);
		}
		smallurl = intent.getSmallUrl();
		largeUrl = intent.getUrl();
		selectPhotoFileid = intent.getSelectPhotoFileid();
		pos = intent.getIndex();

		setImage(smallurl, takePhoto);
		setImage(selectPhotoFileid, selectPhoto);

	}

	private void setImage(String fileid, ImageView view) {
		ALLocalEnv.getLocalEnv().displayImagePluginServerlet(fileid, view);
	}

	private void showDialog(String title, String msg) {

		final AlertDialogCreator mDialogCreator = AlertDialogCreator
				.createOneButtonNormalDialog(this, false);
		mDialogCreator.setTitle(title);
		mDialogCreator.setMessage(msg);
		mDialogCreator.showDialog();
	}

	private void setTextInfo() {
		TextView tv = (TextView) findViewById(R.id.take_photo_info);
		String text = tv.getText().toString();
		String tmp = getString(R.string.TxtTakePicInfo);
		int index = text.indexOf(tmp);
		SpannableStringBuilder style = new SpannableStringBuilder(text);
		style.setSpan(new ForegroundColorSpan(Color.parseColor("#FF9A17")),
				index, index + tmp.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		tv.setText(style);

		tv = (TextView) findViewById(R.id.select_photo_info);
		text = tv.getText().toString();
		tmp = getString(R.string.TxtSelectPicInfo);
		index = text.indexOf(tmp);
		style = new SpannableStringBuilder(text);
		style.setSpan(new ForegroundColorSpan(Color.parseColor("#FF9A17")),
				index, index + tmp.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		tv.setText(style);

	}

	private enum SubmitVAuthStep {
		AL_SUBMIT_VAUTH_NONE, AL_SUBMIT_VAUTH_SELECT_PHOTO, AL_SUBMIT_VAUTH_TAKE_PHOTO, AL_SUBMIT_VAUTH_SUBMIT,
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#initData()
	 */
	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleGetStartVauthResult(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleGetStartVauthResult(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleGetStartVauthResult(data);
		// 请求加V
		dismissLoadingProgress();
		if (data.getResponseCode() == ALXmppEvent.RESPONSE_OK) {

			ALLocalEnv.getLocalEnv().getMyProfile().setVauthed(AUTHETICATIONING);
			setAutheticationState((VauthData) data.getData());
			isTakePhoto = false;
			isSelectPhoto = false;

			showFinishActivityAlertDialog(getString(R.string.TxtVauthIsOngoing));

		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleGetVauthStateResult(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleGetVauthStateResult(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleGetVauthStateResult(data);
		dismissLoadingProgress();
		// 获取V认证状态
		if (data.getResponseCode() == 0) {
			setAutheticationState((VauthData) data.getData());
		}
	}

}
